package com.leyou.common.advice;

import com.leyou.common.exception.LyException;
import com.leyou.common.vo.ExceptionResult;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

/**
 * description: 通用异常处理器，其实本质上就是使用的AOP原理的一个通知
 * @author 朱正磊
 * @date 2021-03-25 16:05:02
 */
@ControllerAdvice
public class CommonExceptionHandler {

    /**
     * description: 处理自定义业务异常
     * @author 朱正磊
     * @date 2021-04-17 15:31:53
     * @param e 自定义业务异常
     * @return 返回异常结果
     */
    @ExceptionHandler(LyException.class)
    public ResponseEntity<ExceptionResult> handleLyException(LyException e) {
        return ResponseEntity.status(e.getExceptionEnum().getCode())
                .body(new ExceptionResult(e.getExceptionEnum()));
    }

    /**
     * description: 处理系统未知异常
     * @author 朱正磊
     * @date 2021-04-17 15:31:59
     * @param e 系统未知异常
     * @return 返回异常结果
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<ExceptionResult> handleException(Exception e) {
        if (e instanceof BindException) {
            return ResponseEntity.status(400).body(
                    new ExceptionResult(400, e.getMessage(), System.currentTimeMillis()));
        }
        return ResponseEntity.status(500).body(
                new ExceptionResult(500, e.getMessage(), System.currentTimeMillis()));
    }

}
